#include "user_login_widget.h"
#include "ui_user_login_widget.h"

#include "QDebug"
#include "error_codes.h"

#include "user_register_widget.h"

#include "net/network_message/network_message.h"
#include "net/network_message/protobuf/user_login.pb.h"

#include "user.h"
#include <QCloseEvent>

UserLoginWidget::UserLoginWidget(QWidget *parent, std::shared_ptr<tcp_client> client) :
    QDialog(parent),
    ui(new Ui::UserLoginWidget),
    clientPtr(client)
{
    ui->setupUi(this);

    ui->userNameLineEdit->setMaxLength(USERNAME_MAX_LENTH);
    ui->passWordLineEdit->setMaxLength(PASSWORD_MAX_LENTH);

    connect(ui->loginPushButton, &QPushButton::clicked, this, [this]() {
        auto userName = ui->userNameLineEdit->text();
        auto passwd = ui->passWordLineEdit->text();
        qDebug() << "user name:" << userName << "password" << passwd;

        int ret = onUserLogin(userName, passwd);
        if (ret == EC_NOT_CONNECTED) {
            qDebug() << "haven't connected to server";
            ui->errorMsgLabel->setText("<font color='red'>错误：连接服务器失败</font>");
        } else if (ret != EC_OK) {
            qDebug() << "user login failed";
            ui->errorMsgLabel->setText("<font color='red'>错误：登录失败，请检查用户名密码是否正确。</font>");
        }
    });

    connect(ui->registerPushButton, &QPushButton::clicked, this, [this]() {
        auto registerWgtPtr = std::make_shared<UserRegisterWidget>(this, clientPtr);
        network_message_handler &msg_handler = network_message_handler::get_instance();
        msg_handler.setUserRegisterWidget(registerWgtPtr);
        registerWgtPtr->exec();
    });
}

UserLoginWidget::~UserLoginWidget()
{
    delete ui;
}

void UserLoginWidget::closeEvent(QCloseEvent *event)
{
    // 在窗口关闭时执行的操作
    qDebug() << "UserLoginWidget is closing";
    event->accept(); // 接受关闭事件
}

int UserLoginWidget::onUserLogin(const QString &username, const QString &passwd)
{
    /* 构造登录消息 */
    UserLoginC2SProto loginMsg;
    loginMsg.set_name(username.toStdString());
    loginMsg.set_password(passwd.toStdString());

    qDebug() << loginMsg.DebugString();
    std::cout << loginMsg.DebugString() << std::endl;

    std::string protobufStr;
    bool ret = loginMsg.SerializeToString(&protobufStr);
    if (!ret) {
        qDebug() << "serialize login message failed";
        return EC_PROTOBUF_SEARILIZE_FAILED;
    }

    network_message msg(MSG_TYPE_C2S_USER_LOGIN, protobufStr);
    auto msgToSend = msg.to_string();
    return clientPtr->send_message(msgToSend);
}

int UserLoginWidget::onUserLoginResponse(int result, const QString &responseMsg,
    uint32_t uid, const std::string &userName)
{
    if (result != 0) {
        isLoginSuccess_ = false;
        qDebug() << "user login failed";
        ui->errorMsgLabel->setText(QString("<font color='red'>错误：登录失败</font>") + responseMsg);

        return EC_LOGIN_FAILED;
    }

    isLoginSuccess_ = true;

    auto &user = User::getInstance();
    user.setUsername(userName);
    user.setUid(uid);
    user.setUserStatus(User::ONLINE);

    this->close();

    return EC_OK;
}
